<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">新增入库单</block>
			<block slot="right"><text class="cuIcon-formfill" @click="submitAction">提交</text></block>
		</cu-custom>
		<form>
			<view class="cu-form-group">
				<view class="title">单据编号</view>
				<view>{{billNumber}}</view>
			</view>
			<view class="cu-form-group">
				<view class="title">单据日期</view>
				<picker mode="date" :value="docDate" start="2024-02-01" end="2025-09-01" @change="dateChange">
					<view class="picker">
						{{docDate}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group" @click="selPurchase">
				<view class="title">采购订单</view>
				<view class="picker" :class="radioIndex>-1?'':'text-red'">
					{{radioIndex>-1?RadioList[radioIndex].bill_no:'请选择'}}
					<text class="cuIcon-right"></text>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">供应商</view>
				<picker @change="supChange" :value="supIndex" :range="supPicker">
					<view class="picker" :class="supIndex>-1?'':'text-red'">
						{{supIndex>-1?supPicker[supIndex]:'请选择'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group" v-if="showMore">
				<view class="title">发票类型</view>
				<picker @change="invChange" :value="invIndex" :range="invPicker">
					<view class="picker">
						{{invPicker[invIndex]}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group" v-if="showMore">
				<view class="title">业务员</view>
				<picker @change="salesChange" :value="salesIndex" :range="salesPicker">
					<view class="picker">
						{{salesIndex>-1?salesPicker[salesIndex]:'请选择'}}
					</view>
				</picker>
			</view>
			<view class="arrowShow" @click="showMore=!showMore">
				<view class="text-gray"><text :class="showMore?'cuIcon-fold':'cuIcon-unfold'"></text></view>
			</view>
			<view class="incoming_Two">
				<view class="indetail_between">
					<view class="intwo_row">
						<view class="incoming_Title" v-for="(item,index) in incomingTArray" :key="index"
							:class="tabIndex==index?'incoming_sel':'incoming_nor'" @click="selAction(index)">{{item}}
							<view class='cu-tag badge' v-if="index&&queryWaitList.length">
								{{queryWaitList.length}}
							</view>
						</view>
					</view>
					<view class="scan-center" @click="scanAction">
						<text class="cuIcon-barcode text-blue" style="font-size: 24px;"></text>
					</view>
				</view>
				<view class="bottom_line"></view>
				<swiper class="flex-bottom-swiper" @change="swiperChange" :current="tabIndex" v-if="radioIndex>-1">
					<swiper-item class="flex-swiper-item">
						<view class="inner_One" v-for="(item,index) in purchaseMainList" :key="index">
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">源单分录号:</view>
									<view class="text-blue">{{item.srcNo}}</view>
								</view>
								<view class="text-red" @click="warehouseAction(index)" v-if="item.sestate">
									添加入库
									<text class="cuIcon-right"></text>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">物料:</view>
									<view class="row_message">{{item.materialId_dictText}}</view>
								</view>
								<view class="intwo_row">
									<view class="row_text">规格型号:</view>
									<view class="row_message">{{item.materialModel}}</view>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">结算数量:</view>
									<view class="text-df margin-left2 text-blue">{{item.settleQty}}</view>
								</view>
								<view class="intwo_row">
									<view class="row_text">单位:</view>
									<view class="row_message">{{item.unitId_dictText}}</view>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">入库数量:</view>
									<view class="text-df margin-left2 text-blue">{{item.qty}}</view>
								</view>
								<view class="intwo_row">
									<view class="row_text">结算金额:</view>
									<view class="text-df margin-left2 text-blue">{{item.settleAmt}}</view>
								</view>
							</view>
						</view>
					</swiper-item>
					<swiper-item class="flex-swiper-item">
						<view class="inner_One" v-for="(item,index) in queryWaitList" :key="index">
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">源单分录号:</view>
									<view class="text-blue">{{item.srcNo}}</view>
								</view>
								<view @click="delhouseAction(index)">
									<text class="cuIcon-roundclosefill text-blue" style="font-size: 24px;"></text>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">物料:</view>
									<view class="row_message">{{item.materialId_dictText}}</view>
								</view>
								<view class="intwo_row">
									<view class="row_text">规格型号:</view>
									<view class="row_message">{{item.materialModel}}</view>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row" @click="showActSheet(index)">
									<view :class="item.warehouseName?'':'text-red'">仓库:</view>
									<div class="margin-left text-df text-blue">{{item.warehouseName}}</div>
								</view>
								<view class="intwo_row">
									<view class="row_text">批次:</view>
									<view class="row_message">{{item.batchNo}}</view>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">入库数量:</view>
									<view class="text-df margin-left2 text-blue">{{item.qty}}</view>
								</view>
								<view class="intwo_row">
									<view class="row_text">单位:</view>
									<view class="row_message">{{item.unitId_dictText}}</view>
								</view>
							</view>
							<view class="indetail_between">
								<view class="intwo_row">
									<view class="row_text">含税单价:</view>
									<view class="text-df margin-left2 text-blue">{{item.price}}</view>
								</view>
								<view class="intwo_row">
									<view class="row_text">含税金额:</view>
									<view class="text-lg margin-left2 text-orange">¥{{item.amt}}</view>
								</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
		</form>
		<view class="cu-modal bottom-modal" :class="modalName=='RadioModal'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<view class="cu-form-group">
					<view class="title">单据编号</view>
					<input placeholder="编号" name="input" v-model="billNoSel"
						style="background-color: aliceblue"></input>
					<view class="action text-blue" @tap="confirModal">确定</view>
				</view>
				<view class="cu-form-group">
					<view class="title">供应商</view>
					<picker @change="superChange" :value="superIndex" :range="supPicker">
						<view class="picker">
							{{superIndex>-1?supPicker[superIndex]:'请选择'}}
						</view>
					</picker>
				</view>
				<radio-group class="block" @change="RadioChange">
					<view class="cu-list menu text-left">
						<view class="flex-sub flex-between marginTitle">
							<view class="flex-3">单据编号</view>
							<view class="flex-1">日期</view>
							<view class="flex-1">供应商</view>
						</view>
						<view class="cu-item" v-for="(item,index) in showRadioList" :key="index">
							<label class="flex justify-between align-center flex-sub">
								<radio class="round" v-show="false" :checked="radioIndex==index?true:false"
									:value="'radio' + index"></radio>
								<view class="flex-sub flex-between">
									<view class="flex-3">{{item.bill_no}}</view>
									<view class="flex-1">{{item.bill_date.substring(5,10)}}</view>
									<view class="flex-1">{{item.sales}}</view>
								</view>
							</label>
						</view>
					</view>
				</radio-group>
			</view>
		</view>
	</view>
</template>

<script>
	import tip from '@/common/util/tip.js';
	export default {
		data() {
			return {
				billNoSel: '',
				showMore: false,
				billNumber: '',
				supIndex: -1,
				superIndex: -1,
				invIndex: 0,
				salesIndex: -1,
				orderIndex: -1,
				radioIndex: -1,
				modalName: '',
				supPicker: [],
				housePicker: [],
				basSupplierList: [],
				basWarehouseList: [],
				invPicker: [],
				salesPicker: [],
				basSysUserList: [],
				operatorName: '',
				docDate: '2024-01-01',
				RadioList: [],
				showRadioList: [],
				tabIndex: 0,
				purchaseMainList: [],
				queryWaitList: [],
				incomingTArray: ['采购订单明细', '入库单明细']
			};
		},
		onLoad: function(option) {
			console.log("incomingForm==onLoad>>")
			let datetime = new Date();
			let timestamp = datetime.getTime().toString();
			let year = datetime.getFullYear()
			let month = datetime.getMonth() + 1
			let day = datetime.getDate()
			month = month > 9 ? month : '0' + month
			day = day > 9 ? day : '0' + day
			this.docDate = year + '-' + month + '-' + day
			this.billNumber = "CGRK-" + year + month + day + '-' + timestamp.substring(timestamp.length - 5);
			this.getBasSupplier();
			this.getBasWarehouse();
			this.getInvoiceDictItems();
			this.getSysUser();
			setTimeout(() => {
				this.getPurchaseData();
			}, 1200)
		},
		onShow: function() {
			// #ifdef APP-PLUS
			// 监听键按下事件
			plus.globalEvent.addEventListener('keydown', function(KeyEvent) {
				console.log("监听键按下事件：" + KeyEvent.keyCode + "");
				// plus.nativeUI.showWaiting("监听键按下事件：" + KeyEvent.keyCode + "");
				// if(KeyEvent.keyCode == 13){
				//  uni.showToast({
				//      title:"监听回车事件"
				//  });
				// }

			});

			// #endif

		},
		created() {
			console.log("created==>>")
		},
		methods: {
			dateChange(e) {
				this.docDate = e.detail.value
			},
			supChange(e) {
				this.supIndex = e.detail.value
			},
			superChange(e) {
				this.superIndex = e.detail.value
				let superId = this.basSupplierList[this.superIndex]['value']
				console.log('superId==>>', superId)
				console.log('RadioList==>>', this.RadioList)
				this.showRadioList = this.RadioList.filter((item) => {
					console.log('item.supplier_id==>>', item.supplier_id)
					return item.supplier_id == superId
				})
			},
			invChange(e) {
				this.invIndex = e.detail.value
			},
			salesChange(e) {
				this.salesIndex = e.detail.value
				this.operatorName = this.basSysUserList[this.salesIndex]['value']
			},
			selPurchase() {
				this.modalName = 'RadioModal'
			},
			hideModal(e) {
				this.modalName = ''
				this.showRadioList = this.RadioList
			},
			RadioChange(e) {
				let that = this;
				console.log('detail==>>', e.detail.value)
				this.radioIndex = e.detail.value.substring(5, 6)
				console.log('radioIndex==>>', this.radioIndex)
				this.modalName = ''
				let supplierId = this.showRadioList[this.radioIndex].supplier_id;
				console.log('supplier_id==>>', this.showRadioList[this.radioIndex].supplier_id)
				this.basSupplierList.forEach((item, index) => {
					if (item['value'] == supplierId) {
						console.log('item==>>', item.value)
						that.supIndex = index
					}
				})
				this.purchaseEntryByMainId(this.showRadioList[this.radioIndex].id);
			},
			selAction(index) {
				this.tabIndex = index
			},
			getBasSupplier() {
				console.log("getBasSupplier")
				this.$http.get('/sys/dict/getDictItems/bas_supplier,aux_name,id').then(res => {
					if (res.data.success) {
						console.log("getBasSupplier==>>", res.data.result)
						this.supPicker = (this.basSupplierList = res.data.result).map(item => item.title)
					}
				})
			},
			getBasWarehouse() {
				console.log("getBasWarehouse")
				this.$http.get('/sys/dict/getDictItems/bas_warehouse,aux_name,id').then(res => {
					if (res.data.success) {
						console.log("getBasWarehouse==>>", res.data.result)
						this.housePicker = (this.basWarehouseList = res.data.result).map(item => item.title)
					}
				})
			},
			getInvoiceDictItems() {
				console.log("getInvoiceDictItems")
				this.$http.get('/sys/dict/getDictItems/x_invoice_type').then(res => {
					if (res.data.success) {
						console.log("getInvoiceDictItems==>>", res.data.result)
						this.invPicker = res.data.result.map(item => item.title)
					}
				})
			},
			getSysUser() {
				console.log("getSysUser")
				this.$http.get('/sys/dict/getDictItems/sys_user,realname,username').then(res => {
					if (res.data.success) {
						console.log("getSysUser==>>", res.data.result)
						this.salesPicker = (this.basSysUserList = res.data.result).map(item => item.title)
					}
				})
			},
			purchaseEntryByMainId(itemID) {
				console.log("purchaseEntryByMainId")
				this.$http.get('/purchase/purOrder/queryEntryByMainId/dictText?id=' + itemID).then(res => {
					if (res.data.success) {
						console.log("result", res.data.result)
						this.purchaseMainList = res.data.result;
						if (this.purchaseMainList.length) {
							this.purchaseMainList.forEach((item, index) => {
								item['sestate'] = true;
								item['warehouseName'] = '';
							})

						}
					}
				})
			},
			getPurchaseData(itemID) {
				console.log("getPurchaseData")
				//http://112.25.140.126:20002/jeecg-boot/sys/dict/getDictItems/bas_supplier,aux_name,id
				//http://112.25.140.126:20002/jeecg-boot/sys/dict/getDictItems/x_invoice_type,aux_name,id
				//http://112.25.140.126:20002/jeecg-boot/sys/dict/getDictItems/sys_user,realname,username
				this.$http.get('/online/cgreport/api/getData/1536593055265607681').then(res => {
					if (res.data.success) {
						console.log("result==>>", res.data.result)
						let recordsArray = res.data.result.records;
						if (recordsArray && recordsArray.length) {
							this.showRadioList = this.RadioList = recordsArray.map((item) => {
								return {
									id: item.id,
									bill_no: item.bill_no,
									bill_date: item.bill_date,
									settle_amt: item.settle_amt,
									supplier_id: item.supplier_id,
									sales: this.basSupplierList.find(itm => {
										return itm['value'] == item.supplier_id
									})?.title?.split(' ')[1]
								}
							})
						}
					}
				})
			},
			swiperChange(e) {
				console.log("swiperChange==>>", e.detail.current)
				this.tabIndex = e.detail.current
			},
			warehouseAction(index) {
				this.purchaseMainList[index].sestate = false
				this.queryWaitList.push(this.purchaseMainList[index])
			},
			delhouseAction(index) {
				let delItem = this.queryWaitList[index];
				tip.confirm('确认删除操作', false).then(res => {
					this.queryWaitList.splice(index, 1)
				})
				this.purchaseMainList.forEach((item, index) => {
					if (delItem.id == item.id) {
						item.sestate = true
					}
				})
			},
			showActSheet(index) {
				let that = this
				uni.showActionSheet({
					itemList: this.housePicker,
					success: function(res) {
						console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
						that.queryWaitList[index]['warehouseId'] = that.basWarehouseList[res.tapIndex]['value']
						that.queryWaitList[index]['warehouseName'] = that.housePicker[res.tapIndex]
						console.log(that.queryWaitList[index]);
						that.$forceUpdate();
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			scanAction() {
				uni.scanCode({
					success: (res) => {
						console.log('条码内容：' + res.result); //扫码内容
						// this.spliceFn(res.result)
					}
				});
			},
			submitAction() {
				if (this.supIndex > -1) {
					if (this.radioIndex > -1) {
						if (this.queryWaitList.length) {
							this.addDocument();
						} else {
							tip.error('请添加入库明细');
						}
					} else {
						tip.error('请选择采购订单');
					}
				} else {
					tip.error('请选择供应商');
				}

			},
			addDocument() {
				console.log("addDocument")
				let stkIoEntryList = [];
				let warehouseFlag = true
				let billNoStr = this.RadioList[this.radioIndex].bill_no
				this.queryWaitList.forEach((item, index) => {
					if (!item.warehouseId) {
						warehouseFlag = false
					}
					console.log('queryItem==>>', JSON.stringify(item))
					let entryNo = (index + 1) * 10;
					let stkIoEntryItem = {
						"entryNo": entryNo,
						"srcNo": billNoStr + ':' + entryNo,
						"materialId": item.materialId,
						"materialModel": item.materialModel,
						"stockIoDirection": "1",
						"warehouseId": item.warehouseId,
						"batchNo": this.billNumber + '-' + entryNo,
						"unitId": item.unitId,
						"settleQty": item.settleQty,
						"taxRate": item.taxRate,
						"price": item.price,
						"discountRate": item.discountRate,
						"tax": item.tax,
						"settleAmt": item.settleAmt,
						"swellQty": item.swellQty,
						"qty": item.qty,
						"expense": item.expense,
						"cost": item.amt,
						"invoicedQty": item.invoicedQty,
						"invoicedAmt": item.invoicedAmt,
						"remark": ""
					}
					stkIoEntryList.push(stkIoEntryItem)
				})

				let subParams = {
					"billNo": this.billNumber,
					"billDate": this.docDate,
					"srcBillId": this.RadioList[this.radioIndex].id,
					"srcBillType": "PurOrder",
					"srcNo": billNoStr,
					"stockIoType": "101", //出入库类型
					"supplierId": this.basSupplierList[this.supIndex]['value'],
					"operator": this.operatorName,
					"opDept": "A01",
					"invoiceType": "0", //发票类型
					"hasRp": "1",
					"stkIoEntryList": stkIoEntryList
				};
				if (warehouseFlag) {
					this.$http.post('/stock/stkIo/addDocument/submit', subParams).then(res => {
						if (res.data.success) {
							console.log("result", res.data.result)
							tip.confirm('入库单创建成功', false).then(res => {
								uni.navigateBack({
									delta: 1
								});
							})
						}
					})
				} else {
					tip.error('请选择仓库');
				}

			},
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.flex-between {
		display: flex;
		justify-content: space-between;
		margin-left: 12rpx;
	}

	.marginTitle {
		margin: 24rpx 48rpx;
	}

	.inner_One {
		width: 92%;
		margin: 4%;
		display: flex;
		flex-direction: column;
		border: 1rpx solid #FAF0E6;
		border-radius: 16rpx;
		background-color: white;
		padding: 16rpx;
		box-shadow: 0px 0px 10px 0px rgba(111, 118, 151, 0.1);
	}

	.incoming_Two {
		width: 100%;
		min-height: 56vh;
		margin-top: 16rpx;
		background-color: white;
	}

	.indetail_row {
		width: 100%;
		display: flex;
		padding: 8rpx 16rpx;
		align-items: center;
	}

	.intwo_row {
		display: flex;
		min-width: 32%;
		padding: 8rpx 16rpx;
		align-items: center;
	}

	.indetail_between {
		display: flex;
		justify-content: space-between;
	}

	.indetail_end {
		display: flex;
	}

	.row_text {
		margin: 4rpx;
		font-size: 24rpx;
		color: #8799a3;
	}

	.row_message {
		margin: 4rpx;
		font-size: 24rpx;
	}

	.incoming_Title {
		display: flex;
		margin: 12rpx 24rpx;
		position: relative;
	}

	.incoming_nor {
		font-size: 28rpx;
		color: grey;
	}

	.incoming_sel {
		font-weight: bold;
		font-size: 32rpx;
		color: black;
	}

	.bottom_line {
		width: 96%;
		margin-left: 2%;
		height: 2rpx;
		background-color: #FAF0E6;
	}

	.flex-bottom-swiper {
		width: 100%;
		height: 64vh;
	}

	.flex-swiper-item {
		width: 100%;
		height: 64vh;
		display: flex;
		flex-direction: column;
		overflow-y: scroll;
	}

	.margin-left2 {
		margin-left: 4rpx;
	}

	.scan-center {
		border: 4rpx solid #0081ff;
		border-radius: 12rpx;
		display: flex;
		padding: 2rpx;
		align-items: center;
		margin: 12rpx 24rpx;
	}

	.arrowShow {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.flex-1 {
		flex: 1;
	}

	.flex-2 {
		flex: 2;
	}

	.flex-3 {
		flex: 3;
	}

	.flex-4 {
		flex: 4;
	}

	.flex-5 {
		flex: 5;
	}
</style>